package zsh.controller;

import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import zsh.config.UploadProperty;
import zsh.core.Result;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
@AllArgsConstructor
@RequestMapping("/file")
public class UploadController {
    private UploadProperty uploadProperty;

    @PostMapping("/upload")
    public Result<String> upload ( MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        List<String> supportSuffix = Arrays.asList(".jpg", ".jpeg", ".png", ".gif");
        if (!supportSuffix.contains(suffix)) {
            return Result.error(500,"上传格式有误，请上传jpg,jpeg,png,gif");
        }
        try {
            file.transferTo(new File(uploadProperty.getLocalPath() + file.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error(500, "文件上传异常，请联系管理员");
        }
        return Result.success(file.getOriginalFilename());
    }
    @PostMapping("/uploads")
    public Result<String> uploadFile (MultipartFile[] files) {
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            List<String> supportSuffix = Arrays.asList(".jpg", ".jpeg", ".png", ".gif");
            if (!supportSuffix.contains(suffix)) {
                return Result.error(500,"请上传jpg,jpeg,png,gif");
            }
            try {
                file.transferTo(new File(uploadProperty.getLocalPath()+file.getOriginalFilename()));
            } catch (IOException e) {
               e.printStackTrace();
               return Result.error(500,"上传异常，请联系管理员");
            }

        }
        return Result.success("上传成功");
    }
}
